~ chicken-core (master) /manual/Module (chicken process)
Trap1[[tags: manual]]2[[toc:]]34== Module (chicken process)56This module offers procedures for interacting with subprocesses.78Note:9Errors caused by underlying C calls that10change errno will produce a condition object with an {{errno}}11property, which can be accessed with12{{(get-condition-property <the-condition-object> 'exn 'errno)}}.1314=== Processes1516==== process-execute1718<procedure>(process-execute PATHNAME [ARGUMENT-LIST [ENVIRONMENT-ALIST]])</procedure>1920Replaces the running process with a new process image from the program21stored at {{PATHNAME}}, using the C library function {{execvp(3)}}.22If the optional argument {{ARGUMENT-LIST}} is given, then it should23contain a list of strings which are passed as arguments to the subprocess.24If the optional argument {{ENVIRONMENT-ALIST}} is supplied, then the library25function {{execve(2)}} is used, and the environment passed in26{{ENVIRONMENT-ALIST}} (which should be of the form {{(("<NAME>" . "<VALUE>") ...)}})27is given to the invoked process. Note that {{execvp(3)}} respects the28current setting of the {{PATH}} environment variable while {{execve(3)}} does not.2930This procedure never returns; it either replaces the process with a new one31or it raises an exception in case something went wrong executing the program.3233On Windows, these procedures all have an additional optional parameter34{{EXACT-FLAG}}, which defaults to {{#f}}. When {{#f}} is passed, any35argument string with embedded whitespace will be wrapped in36quotes. When {{#t}} no such wrapping occurs.373839==== process-fork4041<procedure>(process-fork [THUNK [KILLOTHERS?]])</procedure>4243Creates a new child process with the UNIX system call44{{fork()}}. In the parent process this procedure returns a process-object representing the child process45and in the child process {{process-fork}} returns {{#f}}.46If {{THUNK}} is given, then the child process calls it as a procedure47with no arguments and terminates. If {{THUNK}} is given and the48optional argument {{KILLOTHERS?}} is true, then kill all other49existing threads in the child process, leaving only the current thread50to run {{THUNK}} and terminate.5152'''NOTE''': On native Windows builds (all except cygwin), this53procedure is unimplemented and will raise an error.5455==== process-run5657<procedure>(process-run COMMANDLINE)</procedure><br>58<procedure>(process-run COMMAND ARGUMENT-LIST)</procedure>5960Creates a new child process. The process object representing the new process is returned.6162* The single parameter version passes the {{COMMANDLINE}} to the63system shell, so usual argument expansion can take place. Be careful64to properly quote arguments with the {{qs}} procedure to avoid shell65injection vulnerabilities.66* The multiple parameter version directly invokes the {{COMMAND}} with67the {{ARGUMENT-LIST}}, and is vastly preferred over the68single-parameter version because of its better safety.6970==== process-signal7172<procedure>(process-signal PROCESS [SIGNAL])</procedure>7374Sends {{SIGNAL}} to the process with the integer id or prcoess75object {{PROCESS}} using the76UNIX system call {{kill()}}. {{SIGNAL}} defaults to the value77of the variable {{signal/term}}.7879'''NOTE''': On native Windows builds (all except cygwin), this80procedure is unimplemented and will raise an error.8182==== process-spawn8384<procedure>(process-spawn MODE COMMAND [ARGUMENT-LIST [ENVIRONMENT-LIST [EXACT-FLAG]]])</procedure>8586Creates and runs a new process with the given {{COMMAND}} filename and87the optional {{ARGUMENT-LIST}} and {{ENVIRONMENT-LIST}}. {{MODE}}88specifies how exactly the process should be executed and must be one89or more of the {{spawn/...}} flags listed below.9091The {{EXACT-FLAG}}, default {{#f}}, controls quote-wrapping of92argument strings. When {{#t}} quote-wrapping is not performed.9394Returns:95* the exit status when synchronous96* a process object when asynchronous9798'''NOTE''': On all Unix-like builds (all except native MingW-based99Windows platforms), this procedure is unimplemented and will raise an100error.101102<constant>spawn/overlay</constant>103<constant>spawn/wait</constant>104<constant>spawn/nowait</constant>105<constant>spawn/nowaito</constant>106<constant>spawn/detach</constant>107108These variables contains special flags that specify the exact109semantics of {{process-spawn}}:110111* {{spawn/overlay}} replaces the current process with the new one.112* {{spawn/wait}} suspends execution of the current process until the spawned process returns.113* {{spawn/nowait}} does the opposite ({{spawn/nowaito}} is identical, according to the Microsoft documentation) and runs the process asynchronously.114* {{spawn/detach}} runs the new process in the background, without being attached to a console.115116117==== process-wait118119<procedure>(process-wait [PROCESS [NOHANG]])</procedure>120121Suspends the current process until the child process identifier by {{PROCESS}},122which should be a process object or an integer process id (pid),123has terminated using the UNIX system call124{{waitpid()}}. If {{PROCESS}} is not given, then this procedure125waits for any child process. If {{NOHANG}} is given and not126{{#f}} then the current process is not suspended. This procedure127returns three values:128129* {{PID}} or 0, if {{NOHANG}} is true and the child process has not terminated yet.130* {{#t}} if the process exited normally or {{#f}} otherwise.131* either the exit status, if the process terminated normally or the signal number that terminated/stopped the process.132133Note that suspending the current process implies that all threads134are suspended as well.135136The exit status and the flag indicating whether the process returned normally137are also stored in {{PROCESS}}, when given to be retrieved later, if desired.138139On Windows, {{process-wait}} always returns {{#t}} for a terminated140process and only the exit status is available. (Windows does not141provide signals as an interprocess communication method.)142143144==== process-sleep145146<procedure>(process-sleep SECONDS)</procedure>147148Puts the process to sleep for {{SECONDS}}. Returns either 0 if149the time has completely elapsed, or the number of remaining seconds,150if a signal occurred.151152153==== process154155<procedure>(process COMMANDLINE)</procedure><br>156<procedure>(process COMMAND ARGUMENT-LIST [ENVIRONMENT-ALIST ENCODING])</procedure>157158Creates a subprocess and returns a process object, with the input- and output159ports stored in the object, which can be accessed using accessors described160below.161162* The single parameter version passes the string {{COMMANDLINE}} to the host-system's shell that163is invoked as a subprocess.164* The multiple parameter version directly invokes the {{COMMAND}} as a subprocess. The {{ARGUMENT-LIST}}165is directly passed, as is {{ENVIRONMENT-ALIST}}. These arguments have the same form as the ones of {{process-execute}}.166167{{ENCODING}} should be a symbol specifying the encoding to be168used for I/O operations, the default is {{utf-8}}. The encodings for169the returned in and output ports can be subsequently changed by170using the {{port-encoding}} setter.171172Not using the shell may be preferrable for security reasons.173174Once both the input- and output ports are closed, an implicit175{{waitpid(3)}} is done to wait for the subprocess to finish or to reap176a subprocess that has terminated. If the subprocess has not finished,177waiting for it will necessarily block all executing threads. The exit status178and whether the process exitted normally will be stored in the returned179process object to be retrieved later by the accessors described below,180if so desired.181182==== process*183184<procedure>(process* COMMANDLINE)</procedure><br>185<procedure>(process* COMMAND ARGUMENT-LIST [ENVIRONMENT-ALIST ENCODING])</procedure>186187Like {{process}} but connects also to the error-output port ({{stderr}}) of188the subprocess.189190==== process?191==== process-id192==== process-exit-status193==== process-returned-normally?194==== process-input-port195==== process-output-port196==== process-error-port197198<procedure>(process? X)</procedure>199200Returns a boolean indicating whether {{X}} is a process object.201202<procedure>(process-id PROCESS)</procedure>203<procedure>(process-exit-status PROCESS)</procedure>204<procedure>(process-returned-normally? PROCESS)</procedure>205<procedure>(process-input-port PROCESS)</procedure>206<procedure>(process-output-port PROCESS)</procedure>207<procedure>(process-error-port PROCESS)</procedure>208209Accessors for process-object attributes. The ports values are only210defined for processes created with {{process}} or {{process*}} and represent211the input port from212which data written by the sub-process can be read, the output port from213which any data written to will be received as input in the sub-process214and the error port where to which the sub-process directs its error output.215Blocking reads and writes216to or from the ports returned by {{process}} only block the current217thread, not other threads executing concurrently.218219Standard error for the subprocess is linked up to the current220process's standard error (see {{process*}} if you want to reify221its standard error into a separate port).222223=== Shell commands224225The commands below are all string-based. This means you have to be226very careful to properly quote any arguments to subprocesses, to avoid227shell injection bugs which can lead to arbitrary code execution.228229You can quote arguments with the {{qs}} procedure, but it is strongly230recommended you use {{fork}} with {{process-execute}} or the231multi-argument versions of the {{process}}, {{process*}} or232{{process-run}} procedures.233234==== qs235236<procedure>(qs STRING [PLATFORM])</procedure>237238Escapes {{STRING}} suitably for passing to a shell command on {{PLATFORM}}.239{{PLATFORM}} defaults to the value of {{(build-platform)}} and indicates in240which style the argument should be quoted. On Windows systems, the string241is simply enclosed in double-quote ({{"}}) characters, on UNIXish systems,242characters that would have a special meaning to the shell are escaped243using backslash ({{\}}).244245246==== system247248<procedure>(system STRING)</procedure>249250Execute shell command. The functionality offered by this procedure251depends on the capabilities of the host shell. If the forking of a subprocess252failed, an exception is raised. Otherwise the return status of the253subprocess is returned unaltered.254255256On a UNIX system, that value is the raw return value of waitpid(2), which contains signal, core dump and exit status. It is 0 on success. To pull out the signal number or exit status portably requires POSIX calls, but in a pinch you can use something like this:257258<enscript highlight='scheme'>259;; Returns two values: #t if the process exited normally or #f otherwise;260;; and either the exit status, or the signal number if terminated via signal.261(define (process-status rc)262 (define (wait-signaled? x) (not (= 0 (bitwise-and x 127))))263 (define (wait-signal x) (bitwise-and x 127))264 (define (wait-exit-status x) (arithmetic-shift x -8))265 (if (wait-signaled? rc)266 (values #f (wait-signal rc))267 (values #t (wait-exit-status rc))))268269#;> (process-status (system "exit 42"))270#t27142272</enscript>273274==== system*275276<procedure>(system* STRING)</procedure>277278Similar to {{(system STRING)}}, but signals an error should the invoked279program return a nonzero exit status.280281=== Pipes282283==== call-with-input-pipe284==== call-with-output-pipe285286<procedure>(call-with-input-pipe CMDLINE PROC [MODE])</procedure><br>287<procedure>(call-with-output-pipe CMDLINE PROC [MODE])</procedure>288289Call {{PROC}} with a single argument: a input- or output port290for a pipe connected to the subprocess named in {{CMDLINE}}. If291{{PROC}} returns normally, the pipe is closed and any result values292are returned.293294==== close-input-pipe295==== close-output-pipe296297<procedure>(close-input-pipe PORT)</procedure><br>298<procedure>(close-output-pipe PORT)</procedure>299300Closes the pipe given in {{PORT}} and waits until the connected301subprocess finishes. The exit-status code of the invoked process302is returned.303304==== create-pipe305306<procedure>(create-pipe)</procedure>307308The fundamental pipe-creation operator. Calls the C function309{{pipe()}} and returns 2 values: the file-descriptors of the input-310and output-ends of the pipe.311312On Windows, there is an optional parameter {{MODE}}, which defaults313to {{open/binary | open/noinherit}}. This can be {{open/binary}} or314{{open/text}}, optionally or'ed with {{open/noinherit}}.315316317==== open-input-pipe318319<procedure>(open-input-pipe CMDLINE [MODE])</procedure>320321Spawns a subprocess with the command-line string {{CMDLINE}} and322returns a port, from which the output of the process can be read. If323{{MODE}} is specified, it should be the keyword {{#:text}}324(the default) or {{#:binary}}.325326==== open-output-pipe327328<procedure>(open-output-pipe CMDLINE [MODE])</procedure>329330Spawns a subprocess with the command-line string {{CMDLINE}} and331returns a port. Anything written to that port is treated as the input332for the process. If {{MODE}} is specified, it should be the keyword333{{#:text}} (the default) or {{#:binary}}.334335==== pipe/buf336337<constant>pipe/buf</constant>338339This variable contains the maximal number of bytes that can be written340atomically into a pipe or FIFO.341342==== with-input-from-pipe343==== with-output-to-pipe344345<procedure>(with-input-from-pipe CMDLINE THUNK [MODE])</procedure><br>346<procedure>(with-output-to-pipe CMDLINE THUNK [MODE])</procedure>347348Temporarily set the value of349{{current-input-port/current-output-port}} to a port for a350pipe connected to the subprocess named in {{CMDLINE}} and call351the procedure {{THUNK}} with no arguments. After {{THUNK}}352returns normally the pipe is closed and the standard input-/output port353is restored to its previous value and any result values are returned.354355<enscript highlight=scheme>356(with-output-to-pipe357 "gs -dNOPAUSE -sDEVICE=jpeg -dBATCH -sOutputFile=signballs.jpg -g600x600 -q -"358 (lambda ()359 (print #<<EOF360 %!IOPSC-1993 %%Creator: HAYAKAWA Takashi<xxxxxxxx@xx.xxxxxx.xx.xx>361 /C/neg/d/mul/R/rlineto/E/exp/H{{cvx def}repeat}def/T/dup/g/gt/r/roll/J/ifelse 8362 H/A/copy(z&v4QX&93r9AxYQOZomQalxS2w!!O&vMYa43d6r93rMYvx2dca!D&cjSnjSnjjS3o!v&6A363 X&55SAxM1CD7AjYxTTd62rmxCnTdSST0g&12wECST!&!J0g&D1!&xM0!J0g!l&544dC2Ac96ra!m&3A364 F&&vGoGSnCT0g&wDmlvGoS8wpn6wpS2wTCpS1Sd7ov7Uk7o4Qkdw!&Mvlx1S7oZES3w!J!J!Q&7185d365 Z&lx1CS9d9nE4!k&X&MY7!&1!J!x&jdnjdS3odS!N&mmx1C2wEc!G&150Nx4!n&2o!j&43r!U&0777d366 ]&2AY2A776ddT4oS3oSnMVC00VV0RRR45E42063rNz&v7UX&UOzF!F!J![&44ETCnVn!a&1CDN!Y&0M367 V1c&j2AYdjmMdjjd!o&1r!M){( )T 0 4 3 r put T(/)g{T(9)g{cvn}{cvi}J}{($)g[]J}J368 cvx}forall/moveto/p/floor/w/div/S/add 29 H[{[{]setgray fill}for Y}for showpage369 EOF370 ) ) )371</enscript>372373=== Windows specific notes374375Use of UTF8 encoded strings for pathnames is not supported. Windows376uses a 16-bit UNICODE encoding with special system calls for377wide-character support. Only single-byte string encoding can be used.378379---380Previous: [[Module (chicken pretty-print)]]381382Next: [[Module (chicken process signal)]]